import pool from '../config/database.js';

export const ResidentModel = {
  async getAllResidents() {
    try {
      const [rows] = await pool.query('SELECT * FROM residents ORDER BY created_at DESC');
      return rows.map(row => ({
        id: row.id,
        name: row.name,
        age: row.age,
        room: row.room,
        healthStatus: row.health_status,
        emergencyContact: row.emergency_contact
      }));
    } catch (error) {
      throw new Error('Failed to fetch residents');
    }
  },

  async getResidentById(id) {
    try {
      const [rows] = await pool.query('SELECT * FROM residents WHERE id = ?', [id]);
      if (rows.length === 0) return null;
      
      const row = rows[0];
      return {
        id: row.id,
        name: row.name,
        age: row.age,
        room: row.room,
        healthStatus: row.health_status,
        emergencyContact: row.emergency_contact
      };
    } catch (error) {
      throw new Error('Failed to fetch resident');
    }
  },

  async createResident(resident) {
    try {
      const [result] = await pool.query(
        'INSERT INTO residents (name, age, room, health_status, emergency_contact) VALUES (?, ?, ?, ?, ?)',
        [resident.name, resident.age, resident.room, resident.healthStatus, resident.emergencyContact]
      );
      return result.insertId;
    } catch (error) {
      throw new Error('Failed to create resident');
    }
  },

  async updateResident(id, resident) {
    try {
      const [result] = await pool.query(
        'UPDATE residents SET name = ?, age = ?, room = ?, health_status = ?, emergency_contact = ? WHERE id = ?',
        [resident.name, resident.age, resident.room, resident.healthStatus, resident.emergencyContact, id]
      );
      return result.affectedRows > 0;
    } catch (error) {
      throw new Error('Failed to update resident');
    }
  },

  async deleteResident(id) {
    try {
      const [result] = await pool.query('DELETE FROM residents WHERE id = ?', [id]);
      return result.affectedRows > 0;
    } catch (error) {
      throw new Error('Failed to delete resident');
    }
  }
};